package com.laikan.reader.apirequester;

import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.baidu.api.AccessTokenManager;
import com.baidu.api.Baidu;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.QQUserInfoBean;
import com.laikan.reader.core.bean.WBUserInfoBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.AccountManager;
import com.laikan.reader.database.db.DAO;
import com.socks.library.KLog;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by anrun on 9/7/16.
 */
public class LoginRequester {

    /**
     * QQ登录
     */
    public static void qqLogin(TelephonyManager tm, QQUserInfoBean userInfo, final DAO dao) {
        HashMap<String, String> map = new HashMap<>();
        map.put("token", userInfo.getToken());
        map.put("openid", userInfo.getUserID());
        map.put("name", userInfo.getNickname());
        map.put("deviceId", tm.getDeviceId());
        map.put("ua", android.os.Build.MODEL);

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                parseUserInfo(httpResponse.responseContent, dao);
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast("QQ登录失败");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "accounts/thirdUserQQ");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "accounts/thirdUserQQ", map, null, null, requestListener);

    }

    /**
     * 微信登录
     */
    public static void weixinLogin(TelephonyManager tm, String code, final DAO dao) {
        HashMap<String, String> map = new HashMap<>();
        map.put("name", SPUtil.getString("dsf_name", ""));
        map.put("deviceId", tm.getDeviceId());
        map.put("ua", android.os.Build.MODEL);
        map.put("code", code);
        KLog.e("925-3 code = " + code);

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                parseUserInfo(httpResponse.responseContent, dao);
            }

            @Override
            public void onError(VolleyErrorHandler errorHndler) {
                ToastMgr.showShortToast("微信登录失败");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "accounts/thirdUserWeixin");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "accounts/thirdUserWeixin", map, null, null, requestListener);
    }

    /**
     * 新浪微博登录
     */
    public static void weiboLogin(TelephonyManager tm, WBUserInfoBean userInfo, final DAO dao) {
        HashMap<String, String> map = new HashMap<>();
        map.put("token", userInfo.getToken());
        map.put("openid", userInfo.getUserID());
        map.put("name", userInfo.getNickname());
        map.put("deviceId", tm.getDeviceId());
        map.put("ua", android.os.Build.MODEL);

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                parseUserInfo(httpResponse.responseContent, dao);
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast("新浪微博登录失败");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "accounts/thirdUserWeibo");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "accounts/thirdUserWeibo", map, null, null, requestListener);
    }

    /**
     * 百度登录
     *
     */
    public static void baiduLogin(TelephonyManager tm, Baidu baidu, final DAO dao) {
        if (baidu == null) {
            ToastMgr.showLongToast("登录失败");
            return;
        }
        AccessTokenManager atm = baidu.getAccessTokenManager();
        String accessToken = atm.getAccessToken();
        HashMap<String, String> map = new HashMap<>();
        map.put("token", accessToken);
        map.put("deviceId", tm.getDeviceId());
        map.put("ua", android.os.Build.MODEL);

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                parseUserInfo(httpResponse.responseContent, dao);
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast("百度登录失败");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "accounts/thirdUserBaidu");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "accounts/thirdUserBaidu", map, null, null, requestListener);
    }

    private static void parseUserInfo(String json, DAO dao) {
        try {
            JSONObject obj = new JSONObject(json);
            String result = obj.getString("result");
            if (Constants.RESULT_OK.equals(result)) {
                JSONObject data = obj.getJSONObject("data");
                if(AccountManager.getInstance().isSwitchAccount(data.getString("id"))){
                    if(!TextUtils.isEmpty(SPUtil.getString("token", ""))){
                        AccountManager.getInstance().clearAccountData();
                    }
                }
                SPUtil.putString("token", data.getString("token"));
                SPUtil.putString("user_id", data.getString("id"));
                SPUtil.putString("user_name", data.getString("name"));
                SPUtil.putString("user_score", data.getString("score"));
                SPUtil.putString("user_level", data.getString("level"));
                SPUtil.putString("user_icon", data.getString("icon"));
                ToastMgr.showShortToast("登录成功");
                SPUtil.putBoolean("switch_account", true);
                SPUtil.putBoolean("login_laikan_setting", true);
                BookShelfRequester.syncBookFromServer();
                dao.distributionTask();
                // 同步本地书架列表
                SPUtil.putBoolean("isGetAssetsGift", false);
                SPUtil.putBoolean("login_success", true);
                LaiKanEvent event = LaiKanEvent.getInstance();
                event.setEventID(LaiKanEvent.EVENT_ID_FINISH_LOGIN);
                LaikanApplication.postEvent(event);
            }else {

                ToastMgr.showShortToast(obj.getString("error_msg"));
            }
        }catch (JSONException e) {
            ToastMgr.showShortToast("解析失败");
            e.printStackTrace();
        }
    }
}
